//
//  SPSliderScrollView.m
//  penzer
//
//  Created by 还带大道 on 2018/11/15.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "SPSliderScrollView.h"

@interface SPSliderScrollView()<UIScrollViewDelegate>

@end

@implementation SPSliderScrollView

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame]){
        [self initUI];
    }
    return self;
}


- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super initWithCoder:aDecoder]){
        [self initUI];
    }
    return self;
}


- (void)initUI
{
    self.backgroundColor = [UIColor whiteColor];
    UIScrollView *scrollView = [UIScrollView new];
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.backgroundColor = [UIColor whiteColor];
    _scrollView = scrollView;
    scrollView.delegate = self;
    scrollView.showsHorizontalScrollIndicator = NO;
    [self addSubview:scrollView];
}



- (void)setViews:(NSArray<UIView *> *)views
{
    _views = views;
    [views enumerateObjectsUsingBlock:^(UIView * _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.scrollView addSubview:view];
    }];
}



- (void)layoutSubviews
{
    [super layoutSubviews];
    self.scrollView.frame = self.bounds;
    CGSize size = self.scrollView.frame.size;
    [self.views enumerateObjectsUsingBlock:^(UIView * _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
        view.frame = CGRectMake(size.width*idx, 0, size.width, size.height);
    }];
    self.scrollView.contentSize = CGSizeMake(size.width*self.views.count, 0);
    
}



- (void)selectedWithPage:(NSInteger)page animateWithDuration:(NSTimeInterval)duration
{
    [UIView animateWithDuration:duration animations:^{
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width*page, 0)];
    }];
    
}


#pragma mark--UIScrollViewDelegate
// 滚动视图减速完成，滚动将停止时，调用该方法。一次有效滑动，只执行一次。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:self.scrollView]) {
        NSInteger page = scrollView.contentOffset.x/scrollView.frame.size.width;
        !self.scrollViewDidEndDeceleratingBlock?:self.scrollViewDidEndDeceleratingBlock(page);
    }
}



#pragma mark--getter&&setter

@end
